package org.lhg.activiti.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.lhg.activiti.model.MyProcessDefinition;
import org.lhg.activiti.model.PageBean;
import org.lhg.activiti.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/processDefinition")
public class ProcessDefinitionController {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private HistoryService historyService;

    /**
     * 流程定义查询
     * @param page
     * @param limit
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public CommonResult<JSONObject> list(@RequestParam(value="page",defaultValue="0")String page, @RequestParam(value="limit",defaultValue="0")String limit)throws Exception{
        PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(limit));
        // 返回带分页的结果集合
        List<ProcessDefinition> processDefinition=repositoryService.createProcessDefinitionQuery() .orderByProcessDefinitionId().desc().latestVersion().listPage(pageBean.getStart(), pageBean.getPageSize());
        // 获取总记录数
        long total=repositoryService.createProcessDefinitionQuery().count();
        List<MyProcessDefinition> processList=new ArrayList<MyProcessDefinition>();

        for(ProcessDefinition p:processDefinition){
            MyProcessDefinition myProcessDefinition=new MyProcessDefinition();
            myProcessDefinition.setId(p.getId());
            myProcessDefinition.setName(p.getName());
            myProcessDefinition.setKey(p.getKey());
            myProcessDefinition.setVersion(p.getVersion());
            myProcessDefinition.setResourceName(p.getResourceName());
            myProcessDefinition.setDiagramResourceName(p.getDiagramResourceName());
            myProcessDefinition.setDeploymentId(p.getDeploymentId());
            processList.add(myProcessDefinition);
        }
        JSONObject result=new JSONObject();
        JSONArray jsonArray= JSONArray.parseArray(JSON.toJSONString(processList));
        result.put("rows", jsonArray);
        result.put("total", total);
        return CommonResult.success(result);
    }

    /**
     * 查看流程图
     * @param deploymentId
     * @param diagramResourceName
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/showView",method = RequestMethod.GET)
    public void showView(@RequestParam("deploymentId") String deploymentId, @RequestParam("diagramResourceName") String diagramResourceName, HttpServletResponse response)throws Exception{
        InputStream inputStream=repositoryService.getResourceAsStream(deploymentId, diagramResourceName);
        byte[] b = new byte[1024];
        int len = -1;

        while ((len = inputStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }
    }

    /**
     * 查看流程图
     * @param taskId
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/showViewByTaskId",method = RequestMethod.GET)
    public void showViewByTaskId(@RequestParam String taskId,HttpServletResponse response)throws Exception{
        HistoricTaskInstance hti=historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        String processDefinitionId=hti.getProcessDefinitionId(); // 获取流程定义id
        ProcessDefinition pd=repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        InputStream inputStream=repositoryService.getResourceAsStream(pd.getDeploymentId(), pd.getDiagramResourceName());
        byte[] b = new byte[1024];
        int len = -1;

        while ((len = inputStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }
    }

}
